package com.guanghua.brick.security.extend;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guanghua.brick.html.tag.WebAppContextTag;
import com.guanghua.brick.security.DefaultAuthenticated;
import com.guanghua.brick.security.IAuthenticated;
import com.guanghua.brick.security.SecurityUtil;
import com.guanghua.brick.util.SpringBeanUtil;


/**
 * @version 	1.0
 * @author
 */
public class LoginFilter implements Filter {
	
	//没有登陆的提示页面
	private String noLoginPage = "/nologin.jsp";
	private String[] filterExcludePattern = null;
	private boolean avail = false;
	private boolean createDefaultAuthenticated = false;
	private String defaultAuthenticatedSpringBeanId = null;
	
	public void destroy() {}
	
	public void init(FilterConfig config) throws ServletException {
		if (config.getInitParameter("noLoginPage") != null)
			noLoginPage = config.getInitParameter("noLoginPage");
		
		if (config.getInitParameter("excludePattern") != null) {
			filterExcludePattern = config.getInitParameter("excludePattern").split(",");
		}
		avail = "true".equals(config.getInitParameter("avail"));
		createDefaultAuthenticated = "true".equals(config.getInitParameter("createDefaultAuthenticated"));
		defaultAuthenticatedSpringBeanId = config.getInitParameter("defaultAuthenticatedSpringBeanId");
	}

	/**
	* @see javax.servlet.Filter#void (javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	*/
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
		if (!avail) chain.doFilter(req, resp);
		
		//获取URL
		String url = ((HttpServletRequest)req).getRequestURL().toString();
				
		if (matchExcludeFilterPattern(url)) {
			chain.doFilter(req, resp);
			return;
		} 
		
		//已经登陆
		if (SecurityUtil.isLogin((HttpServletRequest)req))
			chain.doFilter(req, resp);
		//没有登陆
		else {
			//生成默认的登录，便于开发
			if (createDefaultAuthenticated) {
				//利用spring生成登陆人
				IAuthenticated authenticated = null;
				if (defaultAuthenticatedSpringBeanId != null)
					authenticated = (IAuthenticated)SpringBeanUtil.getBeanFactory().getBean(defaultAuthenticatedSpringBeanId);
				else
					authenticated = new DefaultAuthenticated();
				((HttpServletRequest) req).getSession().setAttribute(IAuthenticated.AUTHENTICATED_KEY, authenticated);
				chain.doFilter(req, resp);
			} else {
				HttpServletResponse httpResp = (HttpServletResponse) resp;
				httpResp.sendRedirect(getNoLoginPage((HttpServletRequest)req));
			}
		}
	}

	
	
	
	//校验是否是不需要检查login的资源
	private boolean matchExcludeFilterPattern(String url) {
		//通用的js,css,jpg,gif都不用filter
        if (url.endsWith(".js") || url.endsWith(".css") || 
        	url.endsWith(".jpg") || url.endsWith(".gif") ||
        	url.endsWith(".jar") || url.endsWith(".class") ||
        	url.endsWith(".png")
        	)
            return true;

        //没有登陆或者没有权限的页面也是不需要filter的
        if (url.endsWith(this.noLoginPage) || 
        	url.endsWith("/index.jsp") ||
        	url.endsWith("/index.html") ||
        	url.endsWith("/index.htm") ||
        	url.endsWith("/")) 
        	return true;
        
        //验证配置的过滤
        if (filterExcludePattern == null) return false;
        for (int i = 0; i < filterExcludePattern.length; i++) {
            String pattern = filterExcludePattern[i];
           if (url.matches(pattern)) return true;
        }
        
        return false;

	}
	
	//获取提示没有登陆页面
	private String getNoLoginPage(HttpServletRequest req) {
		return WebAppContextTag.getWebAppContext((HttpServletRequest)req) + this.noLoginPage;
	}

}
